import _regeneratorRuntime from "@babel/runtime/regenerator";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _assertThisInitialized from "@babel/runtime/helpers/esm/assertThisInitialized";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
var _excluded = ["columns"];
import React from 'react';
import { Table } from 'antd';
import request from "../../utils/request";
import { getCurrentOrganizationId, getResponse } from "../../utils/utils";
import { getEnvConfig } from "../../utils/iocUtils";
import intl from "../../utils/intl";

var CustomTable = /*#__PURE__*/function (_React$Component) {
  _inherits(CustomTable, _React$Component);

  var _super = _createSuper(CustomTable);

  function CustomTable(props) {
    var _this;

    _classCallCheck(this, CustomTable);

    _this = _super.call(this, props);

    _this.onColumnFilter = function () {
      var customColumns = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
      var customCode = _this.props.customCode;
      var tenantId = getCurrentOrganizationId();

      if (customColumns && customColumns.length > 0) {
        _this.showLoading('saveCustomColumnsLoading');

        return request("".concat(_this.config.CPAAS_PLATFORM, "/v1/").concat(tenantId, "/custom/table/").concat(customCode), {
          method: 'POST',
          body: customColumns
        }).then(function (res) {
          if (getResponse(res)) {
            _this.setState({
              customColumns: customColumns
            });
          }
        }).finally(function () {
          _this.hiddenLoading('saveCustomColumnsLoading');
        });
      }
    };

    var _customCode = props.customCode,
        columns = props.columns;
    _this.state = {
      init: _customCode === undefined,
      customColumns: [],
      tableColumns: columns,
      saveCustomColumnsLoading: false // 保存 customColumns 时的loading

    };
    _this.config = getEnvConfig();
    _this.showLoading = _this.showLoading.bind(_assertThisInitialized(_this));
    _this.hiddenLoading = _this.hiddenLoading.bind(_assertThisInitialized(_this));
    return _this;
  }

  _createClass(CustomTable, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var customCode = this.props.customCode;

      if (customCode) {
        this.loadHiddenColumns(customCode);
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this$state = this.state,
          init = _this$state.init,
          _this$state$customCol = _this$state.customColumns,
          customColumns = _this$state$customCol === void 0 ? [] : _this$state$customCol,
          _this$state$tableColu = _this$state.tableColumns,
          tableColumns = _this$state$tableColu === void 0 ? [] : _this$state$tableColu,
          _this$state$saveCusto = _this$state.saveCustomColumnsLoading,
          saveCustomColumnsLoading = _this$state$saveCusto === void 0 ? false : _this$state$saveCusto;

      var _this$props = this.props,
          columns = _this$props.columns,
          restProps = _objectWithoutProperties(_this$props, _excluded); // 用户个性化 Table 菜单的国际化


      var filterBarLocale = {
        display: intl.get('cpaas.common.userUI.view.filterBar.display').d('显示'),
        field: intl.get('cpaas.common.userUI.view.filterBar.field').d('字段'),
        fixedLeft: intl.get('cpaas.common.userUI.view.filterBar.lock').d('lock'),
        orderSeq: intl.get('cpaas.common.userUI.view.filterBar.orderSeq').d('排序')
      };
      return init ? /*#__PURE__*/React.createElement(Table, Object.assign({
        columns: tableColumns,
        loading: saveCustomColumnsLoading
      }, restProps, {
        filterBarLocale: filterBarLocale,
        customColumns: customColumns,
        onCustomColumnFilter: this.onColumnFilter
      })) : null;
    }
  }, {
    key: "showLoading",
    value: function showLoading(loadingProp) {
      this.setState(_defineProperty({}, loadingProp, true));
    }
  }, {
    key: "hiddenLoading",
    value: function hiddenLoading(loadingProp) {
      this.setState(_defineProperty({}, loadingProp, false));
    }
  }, {
    key: "loadHiddenColumns",
    value: function () {
      var _loadHiddenColumns = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(code) {
        var tenantId, customColumns, tenantCustomColumns, userCustomColumns, _this$calculateCustom, calculateCustomColumns, tableColumns;

        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                tenantId = getCurrentOrganizationId();
                _context.prev = 1;
                _context.next = 4;
                return request("".concat(this.config.CPAAS_PLATFORM, "/v1/").concat(tenantId, "/custom/table/").concat(code));

              case 4:
                customColumns = _context.sent;

                if (customColumns && customColumns instanceof Array) {
                  tenantCustomColumns = customColumns.filter(function (col) {
                    return col.dimensionType === 'TENANT';
                  });
                  userCustomColumns = customColumns.filter(function (col) {
                    return col.dimensionType === 'USER';
                  });
                  _this$calculateCustom = this.calculateCustomColumns(tenantCustomColumns, userCustomColumns), calculateCustomColumns = _this$calculateCustom.customColumns, tableColumns = _this$calculateCustom.tableColumns;
                  this.setState({
                    customColumns: calculateCustomColumns,
                    tableColumns: tableColumns
                  });
                }

              case 6:
                _context.prev = 6;
                this.setState({
                  init: true
                });
                return _context.finish(6);

              case 9:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this, [[1,, 6, 9]]);
      }));

      function loadHiddenColumns(_x) {
        return _loadHiddenColumns.apply(this, arguments);
      }

      return loadHiddenColumns;
    }()
    /**
     * 保存修改的 customColumns
     * 如果保存成功 更新 Table 中的 customColumns
     */

  }, {
    key: "calculateCustomColumns",
    value:
    /**
     * 通过比较 租户级 和 用户级 的区别 来 计算出 合并过后的 customColumns
     * 以及 过滤后的 columns
     */
    function calculateCustomColumns() {
      var tenantCustomColumns = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
      var userCustomColumns = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
      var hiddenByTenantFields = []; // 存储在 租户级隐藏的 field

      var customColumns = []; // 存储 合并的 customColumn

      var _this$props$columns = this.props.columns,
          columns = _this$props$columns === void 0 ? [] : _this$props$columns; // 拿到原始的 columns

      tenantCustomColumns.forEach(function (customColumn) {
        if (customColumn.hidden === 1) {
          hiddenByTenantFields.push(customColumn.fieldKey);
        } else {
          customColumns.push(customColumn);
        }
      });
      userCustomColumns.forEach(function (customColumn) {
        var hasHiddenByTenant = hiddenByTenantFields.some(function (hiddenFieldKey) {
          return hiddenFieldKey === customColumn.fieldKey;
        });

        if (hasHiddenByTenant) {
          return;
        }

        var tenantCustomColumnIndex = customColumns.findIndex(function (c) {
          return c.fieldKey === customColumn.fieldKey;
        });

        if (tenantCustomColumnIndex !== -1) {
          customColumns[tenantCustomColumnIndex] = customColumn;
        } else {
          customColumns.push(customColumn);
        }
      }); // 计算 经过租户级 过滤的 columns

      var tableColumns = columns.filter(function (column, index) {
        return (// 只要 hiddenByTenantFields 中有 就 不出现在新的 TableColumns 中
          !hiddenByTenantFields.some(function (hiddenFieldKey) {
            return (column.key || column.dataIndex || index || '') === hiddenFieldKey;
          })
        );
      });
      return {
        tableColumns: tableColumns,
        customColumns: customColumns
      };
    }
  }]);

  return CustomTable;
}(React.Component);

export { CustomTable as default };